import {
  McpServer,
  ResourceTemplate,
} from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

function getServer(mcpServerOptions) {
  // Create an MCP server
  const server = new McpServer(mcpServerOptions);

  // Add an addition tool
  server.tool("add", { a: z.number(), b: z.number() }, async ({ a, b }) => ({
    content: [{ type: "text", text: String(a + b) }],
  }));

  // Simple tool with parameters
  server.tool(
    "calculate-bmi",
    {
      weightKg: z.number(),
      heightM: z.number(),
    },
    async ({ weightKg, heightM }) => ({
      content: [
        {
          type: "text",
          text: String(weightKg / (heightM * heightM)),
        },
      ],
    })
  );

  // Async tool with external API call
  server.tool("fetch-weather", { city: z.string() }, async ({ city }) => {
    const response = await fetch(`https://api.weather.com/${city}`);
    const data = await response.text();
    return {
      content: [{ type: "text", text: data }],
    };
  });

  // Add a dynamic greeting resource
  server.resource(
    "greeting",
    new ResourceTemplate("greeting://{name}", { list: undefined }),
    async (uri, { name }) => ({
      contents: [
        {
          uri: uri.href,
          text: `Hello, ${name}!`,
        },
      ],
    })
  );

  // Static resource
  server.resource("config", "config://app", async (uri) => ({
    contents: [
      {
        uri: uri.href,
        text: "App configuration here",
      },
    ],
  }));

  // Dynamic resource with parameters
  server.resource(
    "user-profile",
    new ResourceTemplate("users://{userId}/profile", { list: undefined }),
    async (uri, { userId }) => ({
      contents: [
        {
          uri: uri.href,
          text: `Profile data for user ${userId}`,
        },
      ],
    })
  );

  server.prompt("review-code", { code: z.string() }, ({ code }) => ({
    messages: [
      {
        role: "user",
        content: {
          type: "text",
          text: `Please review this code:\n\n${code}`,
        },
      },
    ],
  }));
  
  return server;
}

export default getServer;

// // Start receiving messages on stdin and sending messages on stdout
// const transport = new StdioServerTransport();
// await server.connect(transport);
